package cn.itcast.servlet;

import cn.itcast.domain.Student;
import cn.itcast.utils.DataSourceUtil;
import cn.itcast.utils.JDBCUtil;
import org.junit.Test;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

// TODO: 2020/7/5
public class templateDemo {
    private JdbcTemplate template = new JdbcTemplate(DataSourceUtil.getDataSouce());


    @Test //查询所有
    public void findAll() {
        List<Student> students = template.query("select * from student", new BeanPropertyRowMapper<Student>(Student.class));
        System.out.println(students);

    }

    @Test //根据id查询
    public Student findById() {
        Student student = null;
        try {
            student = template.queryForObject("select * from student where sid = ?",
                    new BeanPropertyRowMapper<Student>(Student.class), 3);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        return student;
        //System.out.println(student);
    }

    @Test //查询学生表中的总记录数
    public void findCount() {

        Integer count = template.queryForObject("select count(*) from student", Integer.class);

        System.out.println(count);

    }
    @Test //修改表中的某一条数据
    public void updateStu() {
       template.update("update student set  name = ?  where sid = ?  ", "王舞", 3);
    }
    @Test //删除表中的一条数据
    public void deleteStuById() {

        template.update("delete from student where sid = ? " ,4);
    }

    @Test //添加一条数据
    public void addStu() {
        Student stu = new Student();
        stu.setSid(4);
        stu.setName("赵柳");
        stu.setAge(16);
        Date birthday = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
        sdf.format(birthday);
        stu.setBirthday(birthday);
        template.update("insert into student values (?,?,?,?)",stu.getSid(),stu.getName(),stu.getAge(),stu.getBirthday());
    }


}
